
package com.bear.cmcc.NetTestHTTP.util;

import com.bear.cmcc.NetTestHTTP.NetworkTestApp;
import com.bear.cmcc.NetTestHTTP.R;
import com.bear.cmcc.NetTestHTTP.SplashScreenActivity;
import com.bear.cmcc.NetTestHTTP.component.InfoSubBean;
import com.bear.cmcc.NetTestHTTP.component.MenuBean;
import com.bear.cmcc.NetTestHTTP.component.json.respond.LoginRespond;
import com.bear.cmcc.NetTestHTTP.constant.HttpConstant;
import com.bear.cmcc.NetTestHTTP.constant.MyCommonConstant;
import com.bear.cmcc.NetTestHTTP.httpUtil.HttpUtil;
import com.bear.cmcc.NetTestHTTP.service.NetSpeedInfoService;
import com.bear.cmcc.NetTestHTTP.service.NetTestService;
import com.bear.cmcc.NetTestHTTP.service.NetUpdateVersionService;
import com.bear.cmcc.NetTestHTTP.ui.activity.AbstractActivity;
import com.bear.cmcc.NetTestHTTP.ui.activity.CityInfoActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ServiceInfo;
import android.content.res.Resources.NotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.regex.Pattern;

/**
 * 整个工程通用工具类。
 * 
 * @author suchangjun
 */
public class MyCommonUtil {

    private static final String TAG = "MyCommonUtil";

    public static void showMessage(Context context, int messageId) {
        if (context != null) {
            Toast.makeText(context, context.getString(messageId), Toast.LENGTH_LONG).show();
        }
    }

    public static void showMessage(Context context, String message) {
        if (context != null) {
            Toast.makeText(context, message, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 分享功能。
     * 
     * @param context
     * @param title 分享的标题。
     * @param shareMessasge 分享的内容。
     */
    public static void share(Context context, String title, String shareMessasge) {

        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, title);
        intent.putExtra(android.content.Intent.EXTRA_TEXT, shareMessasge);
        context.startActivity(Intent.createChooser(intent, title));

    }

    /**
     * 判断是否是WIFI网络
     * 
     * @param context
     */
    public static boolean isWIFI(Context context) {
        boolean isWifi = false;
        try {
            if (isNetworkAviable(context)) {
                ConnectivityManager connectionManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);

                NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();

                String typeName = networkInfo.getTypeName();

                if (typeName.equalsIgnoreCase(MyCommonConstant.NET_NAME.MOBILE)) {
                    isWifi = false;
                }

                if (typeName.equalsIgnoreCase(MyCommonConstant.NET_NAME.WIFI)) {
                    isWifi = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isWifi;
    }

    /**
     * 判断是否是WIFI网络
     * 
     * @param context
     */
    public static boolean is2G(Context context) {
        try {
            if (isNetworkAviable(context)) {
                ConnectivityManager connectionManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);

                NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();

                String typeName = networkInfo.getTypeName();

                if (typeName.equalsIgnoreCase(MyCommonConstant.NET_NAME.MOBILE)) {
                    String netType = networkInfo.getSubtypeName();
                    if (netType.equalsIgnoreCase(MyCommonConstant.NET_TYPE.EDGE)
                            || netType.equals(MyCommonConstant.NET_TYPE.GPRS)) {
                        return true;
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 获取当前网络类型。
     * 
     * @param context
     * @return {@link MyCommonConstant.NET_TYPE}
     * @see #isNetworkAviable(Context)
     */
    public static String getNetWorkType(Context context) {
        String returnStr = MyCommonConstant.NET_TYPE.UNKNOW;
        try {
            if (isNetworkAviable(context)) {
                ConnectivityManager connectionManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);

                NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();

                String typeName = networkInfo.getTypeName();

                if (typeName.equalsIgnoreCase(MyCommonConstant.NET_NAME.MOBILE)) {
                    String netType = networkInfo.getSubtypeName();
                    if(MyCommonConstant.NET_TYPE.LTE.equalsIgnoreCase(netType))
                    {
                        return MyCommonConstant.NET_TYPE.LTE;
                    }
                    if (netType.equalsIgnoreCase(MyCommonConstant.NET_TYPE.EDGE)
                            || netType.equals(MyCommonConstant.NET_TYPE.GPRS)) {
                        returnStr = MyCommonConstant.NET_TYPE.NET_TYPE_2G;
                    } else {
                        returnStr = MyCommonConstant.NET_TYPE.TD;
                    }
                }

                if (typeName.equalsIgnoreCase(MyCommonConstant.NET_NAME.WIFI)) {
                    returnStr = MyCommonConstant.NET_TYPE.WLAN;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnStr;
    }

    /**
     * 获取当前网络名称。
     * 
     * @param context
     * @return 有可能会返回 null
     * @see #isNetworkAviable(Context)
     */
    public static String getNetWorkName(Context context) {
        String netName = null;
        try {
            if (isNetworkAviable(context)) {
                ConnectivityManager conMan = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = conMan.getActiveNetworkInfo();

                String typeName = networkInfo.getTypeName();

                if (typeName.equalsIgnoreCase(MyCommonConstant.NET_NAME.MOBILE)) {

                    netName = networkInfo.getExtraInfo();

                }

                if (typeName.equalsIgnoreCase(MyCommonConstant.NET_NAME.WIFI)) {

                    WifiManager wifiManager = (WifiManager) context
                            .getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    if (wifiInfo != null) {
                        netName = wifiInfo.getSSID();
                    } else {
                        netName = "canNotGetWifiName";
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return netName;
    }

    /**
     * 获取wifi的强度。
     * 
     * @param context
     * @return
     */
    public static int getWifiStrong(Context context) {
        try {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            if (wifiInfo != null) {
                return wifiInfo.getRssi();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 判断当前网络是否可用。
     * 
     * @param context
     * @return 网络是否可以使用。
     * @see #getNetWorkType(Context)
     */
    public static boolean isNetworkAviable(Context context) {
        if (context == null) {
            return false;
        }
        try {
            ConnectivityManager connectionManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
            return (networkInfo != null && networkInfo.isConnected());
        } catch (Exception e) {
            if (e != null) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 获取当前时间
     * 
     * @return 当前时间
     */
    public static String getCurDate() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmm");
        Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
        return formatter.format(curDate);
    }

    /**
     * 获取当前时间
     * 
     * @return 当前时间
     */
    public static String getCurDateHasMinute() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
        return formatter.format(curDate);
    }

    /**
     * 返回当前时间，格式为2013-03-01 08:00
     * 
     * @return
     */
    public static String getFormatDateTime() {
        String dateTime = getCurDateHasMinute();
        return dateTime.substring(0, 4) + "-" + dateTime.substring(4, 6) + "-"
                + dateTime.substring(6, 8) + " " + dateTime.substring(8, 10) + ":"
                + dateTime.substring(10, 12) + ":" + dateTime.substring(12, 14);
    }

    /**
     * 获取设备ID,如果获取不到那么就是null。
     * 
     * @param context
     * @return
     */
    public static String getDeviceId(Context context) {
        try {
            TelephonyManager telephonyManager = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            return telephonyManager.getDeviceId();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 对设备的 imei MD5加密
     * 
     * @return 加密后的字符串
     */
    public static String getDeviceByMD5(String imei) {
        String device = null;
        if (imei != null) {
            MessageDigest md5;
            byte[] m = null;
            try {
                md5 = MessageDigest.getInstance("MD5");
                md5.update(imei.getBytes());
                m = md5.digest();
                device = byte2hex(m);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
                Log.d(TAG, "getDevice Exception: " + e.getMessage());
            }
        }
        // Log.d(TAG, "我的getDeviceByMD5 : " + device);
        return device;
    }

    /**
     * 把二进制转换成16进制。
     * 
     * @param b
     * @return
     */
    public static String byte2hex(byte[] b) {
        if (b == null)
            return "";
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1)
                hs = hs + "0" + stmp;
            else
                hs = hs + stmp;
        }
        return hs.toUpperCase();
    }

    /**
     * 根据网络类型返回测试下载的文件名
     * 
     * @param b
     * @return
     */
    public static String getDownFileName(String netType) {
        if (netType.equals(MyCommonConstant.NET_TYPE.NET_TYPE_2G))
            return MyCommonConstant.DOWN_FILE_NAME.FILENAME_2G;
        else if (netType.equals(MyCommonConstant.NET_TYPE.TD))
            return MyCommonConstant.DOWN_FILE_NAME.FILENAME_TD;
        else if (netType.equals(MyCommonConstant.NET_TYPE.LTE))
            return MyCommonConstant.DOWN_FILE_NAME.FILENAME_LTE;
        else
            return MyCommonConstant.DOWN_FILE_NAME.FILENAME_WLAN;
    }

    /**
     * 根据城市名称获取城市代码，本方法只是对福建的城市有效。
     * 
     * @param cityName
     * @return 有可能会返回null。
     * @see #getFjCityCodeByCityName(String)
     */
    public static String getFjCityCodeByCityName(String cityName) {
        if (cityName == null) {
            return null;
        }
        // 由于接口问题，不得不在这边定义，等接口中增加城市代码，就不需要这个方法。
        HashMap<String, String> mapCityName = new HashMap<String, String>();
        mapCityName.put("福州市", "0591");
        mapCityName.put("厦门市", "0592");
        mapCityName.put("宁德市", "0593");
        mapCityName.put("莆田市", "0594");
        mapCityName.put("泉州市", "0595");
        mapCityName.put("漳州市", "0596");
        mapCityName.put("龙岩市", "0597");
        mapCityName.put("三明市", "0598");
        mapCityName.put("南平市", "0599");

        mapCityName.put("福州", "0591");
        mapCityName.put("厦门", "0592");
        mapCityName.put("宁德", "0593");
        mapCityName.put("莆田", "0594");
        mapCityName.put("泉州", "0595");
        mapCityName.put("漳州", "0596");
        mapCityName.put("龙岩", "0597");
        mapCityName.put("三明", "0598");
        mapCityName.put("南平", "0599");

        return mapCityName.get(cityName.trim());

    }

    /**
     * 返回福建所有城市代码。
     * 
     * @see #getFjCityCodeByCityName(String)
     */
    public static String[] getFjCityCodeByCityCode() {
        return new String[] {
                "0591", "0592", "0593", "0594", "0595", "0596", "0597", "0598", "0599"
        };

    }

    /**
     * 获取高亮显示颜色。
     * 
     * @return
     */
    public static int getHigthShowColor(Context context) {
        return context.getResources().getColor(R.color.txt_highblue);
    }

    /**
     * 判断某个服务是否在运行。
     * 
     * @param context
     * @param className
     * @return
     */
    public static boolean isServiceRun(Context context, String className) {
        boolean isRun = false;
        try {
            isRun = NetTestUtil.serviceIsWorked(context, className);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return isRun;
    }

    /**
     * 返回当前APK所有在的服务。
     * 
     * @param context
     * @return
     */
    public static ServiceInfo[] getAllService(Context context) {
        ServiceInfo[] ourServices = null;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = null;
            try {
                pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_SERVICES);
            } catch (NameNotFoundException e) {
                Log.i(TAG, e.getMessage());
            }
            if (pi != null) {
                ourServices = pi.services;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ourServices;
    }

    /**
     * 根据手机分辨率，转成px.
     * 
     * @param context
     * @param dpValue
     * @return
     */
    public static int dip2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机分辨率，px-->dp.
     * 
     * @param context
     * @param dpValue
     * @return
     */
    public static int px2dip(Context context, float pxValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 导入数据广播
     * 
     * @param context
     */
    public static void SendImportDataBroad(Context context, boolean isSuccess) {
        Intent intent = new Intent(MyCommonConstant.PrivateActionName.IMPORT_DATA_FINISH_BROAD);
        intent.putExtra(MyCommonConstant.PrivateActionName.IMPORT_DATA_IS_SUCCESS, isSuccess);
        context.sendBroadcast(intent);
    }

    /**
     * 退出
     * 
     * @param context
     */
    public static void exit(Context context) {
        NetworkTestApp.getApp().setHaveLogin(false);
        closeAllService(context);
        Intent intent = new Intent(MyCommonConstant.PrivateActionName.APP_EXIT_FINISH);
        context.sendBroadcast(intent);
    }

    /**
     * 关闭所有的服务
     */
    public static void closeAllService(Context context) {

        Intent intent1 = new Intent(context, NetTestService.class);
        context.stopService(intent1);

        Intent intent2 = new Intent(context, NetSpeedInfoService.class);
        context.stopService(intent2);

        Intent intent3 = new Intent(context, NetUpdateVersionService.class);
        context.stopService(intent3);

        // Intent intent4 = new Intent(context,
        // LocalUpdateVillageDBService.class);
        // context.stopService(intent4);
    }

    /**
     * 返回屏幕宽度
     * 
     * @param context
     * @return
     */
    public static int getWindowWidth(Context context) {
        DisplayMetrics dm = new android.util.DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    /**
     * 返回屏幕高度
     * 
     * @param context
     * @return
     */
    public static int getWindowHeight(Context context) {
        DisplayMetrics dm = new android.util.DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }

    /*
     * 获取系统菜单的列表数据
     */
    public static List<MenuBean> getMenuList(Context context) {
        List<MenuBean> list = new ArrayList<MenuBean>();
        MenuBean b_refresh = new MenuBean();
        MenuBean b_service = new MenuBean();
        MenuBean b_set = new MenuBean();
        // MenuBean b_celldb = new MenuBean();
        MenuBean b_about = new MenuBean();
        MenuBean b_exit = new MenuBean();
        MenuBean b_exportdata = new MenuBean();
        MenuBean b_importdata = new MenuBean();

        MenuBean b_logout = new MenuBean();

        // MenuBean b_not = new MenuBean();

        b_refresh.setTitle(context.getString(R.string.menu_reflesh));
        b_refresh.setId(MyCommonConstant.Menu_options.MENU_REFRESH);

        b_service.setTitle(context.getString(R.string.menu_close_service));
        b_service.setId(MyCommonConstant.Menu_options.MENU_KILL_SERVICE);

        b_set.setTitle(context.getString(R.string.menu_settings));
        b_set.setId(MyCommonConstant.Menu_options.MENU_SET);

        // b_celldb.setTitle(context.getString(R.string.menu_cellDB));
        // b_celldb.setId(MyCommonConstant.Menu_options.MENU_CELLDB);

        b_exportdata.setTitle(context.getString(R.string.menu_exportdata));
        b_exportdata.setId(MyCommonConstant.Menu_options.MENU_EXPORT_DATA);

        b_importdata.setTitle(context.getString(R.string.menu_importdata));
        b_importdata.setId(MyCommonConstant.Menu_options.MENU_IMPORT_DATA);

        b_about.setTitle(context.getString(R.string.menu_aboutus));
        b_about.setId(MyCommonConstant.Menu_options.MENU_ABOUT);

        b_exit.setTitle(context.getString(R.string.menu_exit));
        b_exit.setId(MyCommonConstant.Menu_options.MENU_EXIT);

        b_logout.setTitle(context.getString(R.string.logout));
        b_logout.setId(MyCommonConstant.Menu_options.MENU_LOGOUT);

        // b_not.setTitle("");

        list.add(b_refresh);
        list.add(b_service);
        // list.add(b_celldb);
        list.add(b_exportdata);
        list.add(b_importdata);
        list.add(b_set);
        list.add(b_about);
        list.add(b_logout);
        list.add(b_exit);
        // list.add(b_not);
        return list;
    }

    /**
     * 重新排序频道列表
     * 
     * @param allList 所有的频道
     * @param adapterList 移动之后的频道
     */
    public static List<InfoSubBean> sortInfoSubcrible(List<InfoSubBean> allList,
            List<InfoSubBean> adapterList) {
        if (allList != null && adapterList != null) {
            List<InfoSubBean> list = new ArrayList<InfoSubBean>();
            list.addAll(adapterList);
            int allCount = allList.size();
            for (int i = 0; i < allCount; i++) {
                InfoSubBean b = allList.get(i);
                boolean isExist = false;
                int adapterCount = adapterList.size();
                for (int j = 0; j < adapterCount; j++) {
                    InfoSubBean sb = adapterList.get(j);
                    if (b.getId().equals(sb.getId()) && !sb.getId().equals("0")) {
                        isExist = true;
                        break;
                    }
                }
                if (!isExist) {
                    list.add(b);
                }
            }
            return list;
        } else {
            return null;
        }

    }

    /**
     * 格式化数据显示。
     * 
     * @param data
     * @return
     */
    public static String getFormatString(double data) {
        if (data <= 0) {
            return "0";
        }
        try {
            return String.format("%.0f", data);
        } catch (Exception ex) {
            return "0";
        }
    }

    /**
     * 日期格式化
     * 
     * @param str
     * @return
     */
    public static String dateFormatTo(String date) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return new SimpleDateFormat("MM-dd HH:mm").format(df.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
            return "";
        }
    }

    private static AlertDialog firstUserdlg;

    public static void closeTelNumberDialog() {
        try {
            if (firstUserdlg != null) {
                firstUserdlg.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示输入手机号码对话框。
     * 
     * @param activity
     */
    public static void showInputTelNumberDialog(final Activity activity) {
        // boolean result=false;

        try {
            LayoutInflater factory = LayoutInflater.from(activity);
            View DialogView = factory.inflate(R.layout.firseuserdialog, null);
            final EditText phoneNumET = (EditText) DialogView
                    .findViewById(R.id.firseuser_phonenumET);
            firstUserdlg = new AlertDialog.Builder(activity)
                    .setTitle(R.string.app_name)
                    .setView(DialogView)
                    .setPositiveButton(
                            activity.getResources().getString(R.string.firstuseBtnConfirm),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    try {
                                        Field field = dialog.getClass().getSuperclass()
                                                .getDeclaredField("mShowing");
                                        field.setAccessible(true);
                                        field.set(dialog, false);// 用来设置是否可以关闭的按钮

                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    if (phoneNumET.getText().toString().equals("")) {
                                        MyCommonUtil.showMessage(activity,
                                                R.string.please_input_number);
                                    } else if (phoneNumET.getText().length() < 11) {
                                        MyCommonUtil.showMessage(activity,
                                                R.string.number_too_short);

                                    } else if (!isNumeric(phoneNumET.getText().toString())) {
                                        MyCommonUtil.showMessage(activity,
                                                R.string.you_input_is_not_number);
                                    } else {
                                        SetUtil.setTelNumber(activity, phoneNumET.getText()
                                                .toString());
                                        Log.i(TAG, "当前输入手机号码是:" + SetUtil.getTelNumber(activity));
                                        try {
                                            Field field = dialog.getClass().getSuperclass()
                                                    .getDeclaredField("mShowing");
                                            field.setAccessible(true);
                                            field.set(dialog, true);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        dialog.dismiss();
                                    }
                                }
                            })
                    .setNegativeButton(
                            activity.getResources().getString(R.string.firstuseBtnCancle),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    try {
                                        Field field = dialog.getClass().getSuperclass()
                                                .getDeclaredField("mShowing");
                                        field.setAccessible(true);
                                        field.set(dialog, true);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    activity.finish();
                                }
                            }).create();
            firstUserdlg.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
            firstUserdlg.setCancelable(false);
            firstUserdlg.show();
        } catch (NotFoundException e) {
            e.printStackTrace();
        }

        // return result;
    }

    /**
     * 显示输入手机号码对话框。
     * 
     * @param activity
     */
    public static void showInputTelNumberDialog(final Activity activity, String number) {
        // boolean result=false;

        try {
            LayoutInflater factory = LayoutInflater.from(activity);
            View DialogView = factory.inflate(R.layout.firseuserdialog, null);
            final EditText phoneNumET = (EditText) DialogView
                    .findViewById(R.id.firseuser_phonenumET);
            phoneNumET.setText(number);
            AlertDialog firstUserdlg = new AlertDialog.Builder(activity)
                    .setTitle(R.string.app_name)
                    .setView(DialogView)
                    .setPositiveButton(
                            activity.getResources().getString(R.string.firstuseBtnConfirm),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    try {
                                        Field field = dialog.getClass().getSuperclass()
                                                .getDeclaredField("mShowing");
                                        field.setAccessible(true);
                                        field.set(dialog, false);

                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    if (phoneNumET.getText().toString().equals("")) {
                                        MyCommonUtil.showMessage(activity,
                                                R.string.please_input_number);
                                    } else if (phoneNumET.getText().length() < 11) {
                                        MyCommonUtil.showMessage(activity,
                                                R.string.number_too_short);

                                    } else if (!isNumeric(phoneNumET.getText().toString())) {
                                        MyCommonUtil.showMessage(activity,
                                                R.string.you_input_is_not_number);
                                    } else {
                                        SetUtil.setTelNumber(activity, phoneNumET.getText()
                                                .toString());
                                        Log.i(TAG, "当前输入手机号码是:" + SetUtil.getTelNumber(activity));
                                        try {
                                            Field field = dialog.getClass().getSuperclass()
                                                    .getDeclaredField("mShowing");
                                            field.setAccessible(true);
                                            field.set(dialog, true);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        dialog.dismiss();
                                    }
                                }
                            })
                    .setNegativeButton(
                            activity.getResources().getString(R.string.firstuseBtnCancle),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    try {
                                        Field field = dialog.getClass().getSuperclass()
                                                .getDeclaredField("mShowing");
                                        field.setAccessible(true);
                                        field.set(dialog, true);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    activity.finish();
                                }
                            }).create();
            firstUserdlg.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
            firstUserdlg.setCancelable(false);
            firstUserdlg.show();
        } catch (NotFoundException e) {
            e.printStackTrace();
        }

        // return result;
    }

    /**
     * 显示登录对话框，并且只有登录成功对话框才会消失。
     * 
     * @param activity
     */
    public static void showLoginDialog(final Activity activity) {
        LayoutInflater factory = LayoutInflater.from(activity);
        final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);

        final EditText nameET = (EditText) textEntryView.findViewById(R.id.username_edit);

        final EditText passwordET = (EditText) textEntryView.findViewById(R.id.password_edit);

        final CheckBox autoCheckBox = (CheckBox) textEntryView.findViewById(R.id.auto_login);
        autoCheckBox.setChecked(SetUtil.getIsAuToLogin(activity));
        autoCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SetUtil.setIsAuToLogin(activity, isChecked);
                Log.i(TAG, SetUtil.getIsAuToLogin(activity) + "");
            }
        });

        String[] values = SetUtil.getLoginInfo(activity);
        if (values != null && values.length == 2 && !TextUtils.isEmpty(values[0])
                && !TextUtils.isEmpty(values[1])) {
            nameET.setText(values[0]);
            passwordET.setText(values[1]);
        }

        AlertDialog alertDialog = new AlertDialog.Builder(activity)
                // .setIconAttribute(android.R.attr.alertDialogIcon)
                .setTitle(R.string.alert_dialog_text_entry)
                .setView(textEntryView)
                .setPositiveButton(R.string.dlg_note_btn_confirm,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {

                                setDialogCanDimiss(dialog, false);

                                String name = nameET.getText().toString();
                                String password = passwordET.getText().toString();
                                Log.i("scj", "name " + name + " password" + password);

                                if (TextUtils.isEmpty(name) || TextUtils.isEmpty(password)) {
                                    MyCommonUtil.showMessage(activity,
                                            R.string.name_or_password_no_null);
                                } else {
                                    if (MyCommonUtil.isNetworkAviable(activity)) {

                                        boolean result = startAutoLogin(activity, name.trim(),
                                                password.trim());

                                        if (result) {
                                            setDialogCanDimiss(dialog, true);
                                            dialog.dismiss();

                                            if (activity instanceof AbstractActivity) {
                                                AbstractActivity hand = (AbstractActivity) activity;
                                                hand.refresh();
                                            } else if (activity instanceof SplashScreenActivity) {
                                                SplashScreenActivity hand = (SplashScreenActivity) activity;
                                                hand.startNextActivity();
                                            }

                                        }
                                    } else {
                                        MyCommonUtil.showMessage(activity, R.string.no_network);
                                    }

                                }
                            }

                        })
                .setNegativeButton(R.string.dlg_note_btn_cancel,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {

                                // setDialogCanDimiss(dialog, false);
                                //
                                // MyCommonUtil.showMessage(activity,
                                // R.string.login_message);

                                setDialogCanDimiss(dialog, true);
                                dialog.dismiss();
                                if (activity instanceof AbstractActivity) {
                                    MyCommonUtil.exit(activity);
                                } else if (activity instanceof SplashScreenActivity) {
                                    MyCommonUtil.exit(activity);
                                    activity.finish();
                                }

                            }
                        }).create();

        alertDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        alertDialog.setCancelable(false);
        if (alertDialog != null) {
            alertDialog.show();
        }

    }

    public static boolean startAutoLogin(Activity activity, String name, String password) {
        boolean result = false;
        String[] localVersion = SetUtil.getLocalVersion(activity);
        String versionCode = "";
        String versidonName = "";
        if (localVersion != null && localVersion.length >= 2) {
            versionCode = localVersion[0];
            versidonName = localVersion[1];
        }
        LoginRespond respond = startThreadLogin(activity, name, password, versionCode, versidonName);
        if (respond != null && respond.getErrorCode() == HttpConstant.CODE_SUCCESS) {
            SetUtil.setLoginInfo(activity, name, password);
            NetworkTestApp.getApp().setHaveLogin(true);// 用来记录已经登录
            result = true;
            MyCommonUtil.showMessage(activity, respond.getMessage());

        } else if (respond == null) {
            MyCommonUtil.showMessage(activity, R.string.login_again);
        } else {
            MyCommonUtil.showMessage(activity, respond.getMessage());
        }
        return result;
    }

    /**
     * 启动一个独立线程登录。
     * 
     * @param context
     * @param name
     * @param password
     * @return
     */
    public static LoginRespond startThreadLogin(final Context context, final String name,
            final String password, final String versionCode, final String versidonName) {

        LoginRespond respond = null;
        ExecutorService executor = Executors.newSingleThreadExecutor();
        FutureTask<LoginRespond> future = new FutureTask<LoginRespond>(
                new Callable<LoginRespond>() {
                    public LoginRespond call() {
                        // 真正的任务在这里执行，这里的返回值类型为String，可以为任意类型
                        return HttpUtil.login(context, name, password, versionCode, versidonName);
                    }
                });
        executor.execute(future);
        // 在这里可以做别的任何事情
        try {
            respond = future.get(65, TimeUnit.SECONDS); // 取得结果，同时设置超时执行时间为6秒。同样可以用future.get()，不设置执行超时时间取得结果
        } catch (InterruptedException e) {
            e.printStackTrace();
            future.cancel(true);
        } catch (ExecutionException e) {
            e.printStackTrace();
            future.cancel(true);
        } catch (TimeoutException e) {
            e.printStackTrace();
            future.cancel(true);
        } finally {
            executor.shutdown();
        }
        return respond;

    }

    /**
     * 判断是否数字开头
     * 
     * @param str 判断的字符串
     * @return boolean true有数字，false没数字
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /**
     * 求给定双精度数组中值的方差
     * 
     * @param inputData 输入数据数组
     * @return 运算结果
     */
    public static double getVariance(double[] inputData) {
        int count = getCount(inputData);
        double sqrsum = getSquareSum(inputData);
        double average = getAverage(inputData);
        double result;
        result = (sqrsum - count * average * average) / count;
        return result;
    }

    /**
     * 求给定双精度数组中值的方差(样本方差)
     * 
     * @param inputData 输入数据数组
     * @return 运算结果
     */
    public static int getVarianceTwo(ArrayList<Double> inputData) {
        double result = 0;
        try {
            if (inputData != null && inputData.size() > 0) {

                int count = inputData.size();
                if (count <= 1) {
                    return 0;
                }

                double average = getAverage(inputData);
                double sum = 0;
                double current = 0;
                for (int i = 0; i < count; i++) {
                    current = inputData.get(i);
                    sum = sum + (current - average) * (current - average);
                }
                sum = (sum / (count - 1));
                result = Math.sqrt(sum);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return (int) result;
    }

    /**
     * 求给定双精度数组中值的方差(样本方差)
     * 
     * @param inputData 输入数据数组
     * @return 运算结果
     */
    public static int getVarianceTwo(double[] inputData) {
        double result = 0;
        try {
            if (inputData != null && inputData.length > 0) {

                if (inputData.length <= 1) {
                    return 0;
                }

                int count = getCount(inputData);
                double average = getAverage(inputData);
                double sum = 0;
                for (int i = 0; i < count; i++) {
                    sum = sum + (inputData[i] - average) * (inputData[i] - average);
                }

                sum = (sum / (count - 1));
                result = Math.sqrt(sum);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return (int) result;
    }

    /**
     * @param input Data 输入数据数组
     * @return 运算结果
     */
    public static int getCount(double[] inputData) {
        if (inputData == null)
            return -1;
        return inputData.length;
    }

    /**
     * 求给定双精度数组中值的平方和
     * 
     * @param inputData 输入数据数组
     * @return 运算结果
     */
    public static double getSquareSum(double[] inputData) {
        if (inputData == null || inputData.length == 0)
            return -1;
        int len = inputData.length;
        double sqrsum = 0.0;
        for (int i = 0; i < len; i++) {
            sqrsum = sqrsum + inputData[i] * inputData[i];
        }

        return sqrsum;
    }

    /**
     * 求给定双精度数组中值的平均值
     * 
     * @param inputData 输入数据数组
     * @return 运算结果
     */
    public static double getAverage(ArrayList<Double> inputData) {
        if (inputData == null || inputData.size() == 0)
            return -1;
        int len = inputData.size();
        double result;
        result = getSum(inputData) / len;

        return result;
    }

    /**
     * 求给定双精度数组中值的和
     * 
     * @param inputData 输入数据数组
     * @return 运算结果
     */
    public static double getSum(ArrayList<Double> inputData) {
        if (inputData == null || inputData.size() == 0)
            return -1;
        int len = inputData.size();
        double sum = 0;
        for (int i = 0; i < len; i++) {
            sum = sum + inputData.get(i);
        }
        return sum;
    }

    /**
     * 求给定双精度数组中值的平均值
     * 
     * @param inputData 输入数据数组
     * @return 运算结果
     */
    public static double getAverage(double[] inputData) {
        if (inputData == null || inputData.length == 0)
            return -1;
        int len = inputData.length;
        double result;
        result = getSum(inputData) / len;

        return result;
    }

    /**
     * 求给定双精度数组中值的和
     * 
     * @param inputData 输入数据数组
     * @return 运算结果
     */
    public static double getSum(double[] inputData) {
        if (inputData == null || inputData.length == 0)
            return -1;
        int len = inputData.length;
        double sum = 0;
        for (int i = 0; i < len; i++) {
            sum = sum + inputData[i];
        }
        return sum;
    }

    /**
     * 获取IP地址。
     * 
     * @return
     */
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                    .hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                        .hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e(TAG, ex.toString());
        }
        return null;
    }

    public static String getLocalMacAddress(Context context) {
        String result = "";
        try {
            Object object = context.getSystemService(Context.WIFI_SERVICE);
            if (object != null) {
                WifiManager wifi = (WifiManager) object;
                if (wifi != null) {
                    WifiInfo info = wifi.getConnectionInfo();
                    if (info != null) {
                        result = info.getMacAddress();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 设置对话框是否可以取消.
     * 
     * @param dialog
     * @param can
     */
    private static void setDialogCanDimiss(DialogInterface dialog, boolean can) {
        if (dialog == null) {
            return;
        }
        try {
            Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
            field.setAccessible(true);
            field.set(dialog, can);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 默认打开附件这个界面
     * 
     * @param context
     */
    public static void startFjActivity(Activity activity) {
        Intent it = new Intent(activity, CityInfoActivity.class);
        it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        String currentClickPro = "福建";
        NetworkTestApp.getApp().setCurrentUserClickProvice(currentClickPro);
        it.putExtra("provinceName", currentClickPro);
        it.putExtra(MyCommonConstant.PROVINCE_CODE, "10554");
        activity.startActivity(it);
    }

    /**
     * 用来判断易运维是否已经登录，不用用户名和密码.
     * 
     * @param activity
     * @return
     */
    public static boolean checkHaveLogin(Activity activity) {
        boolean result = false;
        try {
            String[] localVersion = SetUtil.getLocalVersion(activity);
            String versionCode = "";
            String versidonName = "";
            if (localVersion != null && localVersion.length >= 2) {
                versionCode = localVersion[0];
                versidonName = localVersion[1];
            }
            LoginRespond respond = startThreadLogin(activity, "", "", versionCode, versidonName);
            if (respond != null && respond.getErrorCode() == HttpConstant.CODE_SUCCESS) {
                Log.e("scj", "-----------------易运维验证登录成功");
                NetworkTestApp.getApp().setHaveLogin(true);// 用来记录已经登录
                result = true;
                // MyCommonUtil.showMessage(activity, respond.getMessage());

            } else {
                NetworkTestApp.getApp().setHaveLogin(false);// 用来记录已经登录
                Log.e("scj", "-----------------易运维验证登录-------失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
